package com.bolovan.infovaluta.reader;

import java.io.IOException;
import java.math.BigDecimal;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.bolovan.infovaluta.bean.ExchangeRate;
import com.bolovan.infovaluta.bean.ExchangeRateEntry;
import com.bolovan.infovaluta.bean.ExchangeRateSeller;
import com.bolovan.infovaluta.util.RateConstants;
import com.bolovan.infovaluta.util.RateMaps;
import com.bolovan.infovaluta.util.RateUtil;

public class BtReader extends ExchangeReader {

	public BtReader(ExchangeRateSeller seller) {
		super(seller);
	}

	@Override
	public void buildRateMap(ExchangeRate map) throws IOException {
		fetchBT(map);
	}

	private void fetchBT(ExchangeRate map) throws IOException {
		setParsingDate(RateMaps.date);

		Document doc = RateUtil.getDocument(ExchangeRateSeller.BT.getUrl());
		Elements elements = doc.select("table.cp").first().select("tr");
		// first el is the header
		for (int i = 1; i < elements.size(); i++) {
			Element tr = elements.get(i);
			Elements tds = tr.select("td");
			if (tds.size() == 8) {
				String currency = tds.get(1).text();
				BigDecimal bid = new BigDecimal(tds.get(5).text());
				BigDecimal ask = new BigDecimal(tds.get(6).text());

				if (RateConstants.multiplierCurrencyes.contains(currency)) {
					bid = bid.multiply(new BigDecimal(100));
					ask = ask.multiply(new BigDecimal(100));
				}
				map.addToMap(new ExchangeRateEntry(currency, bid, ask));
			}
		}
	}
}
